package com.gitee.linzl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import com.gitee.linzl.domain.Authority;
import com.gitee.linzl.domain.Role;
import com.gitee.linzl.domain.User;
import com.gitee.linzl.repository.AuthorityRepository;
import com.gitee.linzl.repository.RoleRepository;
import com.gitee.linzl.service.UserService;

import lombok.AllArgsConstructor;

@Component
@AllArgsConstructor
public class Init implements CommandLineRunner {
	@Autowired
	private UserService userService;
	@Autowired
	private AuthorityRepository authorityRepository;
	@Autowired
	private RoleRepository roleRepository;
	@Autowired
	private PasswordEncoder passwordEncoder;

	@Override
	public void run(String... strings) throws Exception {
		// 权限
		Authority authority = new Authority();
		authority.setId(1L);
		authority.setName("查询");
		authority.setValue("query");
		authorityRepository.save(authority);

		// 角色
		Role admin = new Role();
		admin.setId(1L);
		admin.setName("管理员");
		admin.setValue("ROLE_ADMIN");
		admin.getAuthorities().add(authorityRepository.findById(1L).get());
		roleRepository.save(admin);

		Role role = new Role();
		role.setId(2L);
		role.setName("普通用户");
		role.setValue("ROLE_USER");
		roleRepository.save(role);

		// 用户
		User fpf = new User();
		fpf.setId(1L);
		fpf.setUsername("fpf");
		fpf.setPassword(passwordEncoder.encode("fpf"));
		fpf.getRoles().add(roleRepository.findById(1L).get());
		userService.createUser(fpf);

		User wl = new User();
		wl.setId(2L);
		wl.setUsername("wl");
		wl.setPassword(passwordEncoder.encode("wl"));
		wl.getRoles().add(roleRepository.findById(2L).get());
		userService.createUser(wl);
	}
}
